package org.wannatrak.android.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.R;
import org.wannatrak.android.helper.IOHelper;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-11-29 05:19:42 +0000 (Tue, 29 Nov 2011) $
 * @Time: 21:30:17
 * @Version: $Revision: 32 $
 * @Id: $Id: ProjectDbOpenHelper.java 32 2011-11-29 05:19:42Z maxtulupov@gmail.com $
 */
public class ProjectDbOpenHelper extends SQLiteOpenHelper{

     private static Context context;

        public ProjectDbOpenHelper(Context context) {
            super(context, ApplicationContext.DB_NAME, null, 2);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            String sql = IOHelper.readResourceAsString(context, R.raw.create_db);
            String[] strings = sql.split(";");
            executeStatements(strings, db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            for (int i = oldVersion + 1; i <= newVersion; i++) {
                String filename = "upgrade_db_" + i;
                int identifier = context.getResources().getIdentifier(filename, "raw", "org.wannatrak.android");
                if (identifier > 0) {
                    String sql = IOHelper.readResourceAsString(context, identifier);
                    Log.d(getClass().getSimpleName(), "Upgrading database from version " + oldVersion + " to "
                            + newVersion + ", which will destroy all old data");
                    executeStatements(sql.split(";"), db);
                } else {
                    Log.e(getClass().getSimpleName(), "impossible upgrade db file is not exist " + filename);
                }
            }
        }

        private void executeStatements(String[] strings, SQLiteDatabase db) {
            for (int i = 0; i < strings.length; i++) {
                String str = strings[i].replace("\n", "").trim().replace("\t", "");
                if (str.length() > 0) {
                    db.execSQL(strings[i]);
                }
            }
        }
}
